package com.lunasoft.client;

import com.lunasoft.protobuf.TESMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author Jierry
 * @version 2016/7/14.
 */
public class ClientHandler extends SimpleChannelInboundHandler<TESMsg.BasicMsg> {

    private static Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelUnregistered:Reconnect");
        final EventLoopGroup loop = ctx.channel().eventLoop();
        loop.schedule(() -> Client.connect(new Bootstrap(), loop), 10L, TimeUnit.SECONDS);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        TESMsg.Message.Builder builder = TESMsg.Message.newBuilder();
        builder.setHeader(101);
        TESMsg.LoginInfo.Builder loginInfo = TESMsg.LoginInfo.newBuilder();
        loginInfo.setUserId(100);
        loginInfo.setToken("tes");
        builder.setLoginInfo(loginInfo);

        ctx.channel().writeAndFlush(builder.build());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                /*心跳处理*/
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                /*读超时*/
                logger.info("READER_IDLE 读超时");
                ctx.disconnect();
            } else if (event.state() == IdleState.WRITER_IDLE) {
                /*写超时*/
                logger.info("WRITER_IDLE 写超时");
            } else if (event.state() == IdleState.ALL_IDLE) {
                /*总超时*/
                logger.info("ALL_IDLE 总超时");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TESMsg.BasicMsg basicMsg) throws Exception {
        if (basicMsg.getTime()==2){
            System.out.print("这是关闭命令\r\n");
        }else{
            System.out.print("这是时间同步："+basicMsg.getTime()+"\r\n");
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        ctx.close();
    }
}
